<template>
    <div>
        <div class="main" ref="main"></div>
    </div>
</template>

<script>
    import WebSocketClient from "../util/webSocketClient"
    import * as echarts from "echarts";

    export default {
        name: "EcharsView",
        data(){
            return {
                wsClient : null,
                myChart :null,
            }
        },
        created(){ // 配置keep-alive后，只有首次加载组件时执行
            this.wsClient = new WebSocketClient("ws://192.168.5.148:3000/product/one/2000");
        },
        mounted(){ // 配置keep-alive后，只有首次加载组件时执行
            this.myChart = echarts.init(this.$refs.main);
            this.myChart.showLoading();  // 异步加载时的延迟动画

            // 监听从服务器实时获取的数据
            this.wsClient.onMessage =  ({data}) => {
                let res = JSON.parse(data);
                console.log(res)
                // 将后端传过来的json数据转换成echarts的数据结构
                let config = {
                    xAxis : {
                        name : res.year,
                        type : "category",
                        data: res.data.map(item => item.city)
                    },
                    yAxis : {
                        type : "value",
                        axisLabel: {
                            formatter : "{value}分"
                        }
                    },
                    tooltip:{
                        trigger :"axis"
                    },
                    legend:{},
                    series: [
                        {
                            type: "bar",
                            name : "一本线",
                            data : res.data.map(item => item['level1'])
                        },
                        {
                            type: "bar",
                            name : "二本线",
                            data : res.data.map(item => item['level2'])
                        }
                    ]
                }
                this.myChart.hideLoading();  // 关闭延迟加载动画
                this.myChart.setOption(config)
            }
        },
        activated(){  // 缓存激活时执行
            this.wsClient.send("begin"); // 再次进入组件时继续推送
        },
        deactivated(){ // 缓存停用时执行
            this.wsClient.send("end"); // 离开组件时停止推送
        },
        beforeDestroy(){
            if(this.wsClient){
                this.wsClient.disconnect(); // 销毁组件时断开与服务端websocket连接
            }
            if(this.myChart){
                this.myChart.dispose(); // 销毁组件前销毁 echarts实例
            }

        }
    }
</script>

<style scoped>
    .main {
        width: 70%;
        height: 80%;
        box-shadow: 1px 1px 10px #333;
        position: absolute;
        top : 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>